/**
 * @(#)NewTaskActivity.java        1.0 2/26/12
 * 
 * Copyright (c) 2012 public static droid main
 * Georgia Institute of Technology, Atlanta, GA
 * All rights reserved.
 */
package edu.gatech.oad.publicstaticdroidmain.taskmanager.ui;

import java.io.IOException;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import edu.gatech.oad.publicstaticdroidmain.taskmanager.model.LocationHelper;
import edu.gatech.oad.publicstaticdroidmain.taskmanager.model.Task;
import edu.gatech.oad.publicstaticdroidmain.taskmanager.model.Task.Recurrence;
import edu.gatech.oad.publicstaticdroidmain.taskmanager.model.TaskManager;

/**
 * An Android activity that enables a user to create a a new task  
 * 
 * 
 * @version 1.0 Feb 22 2012
 * @author Daniel Hull
 */
public class NewTaskActivity extends AbstractTaskManagerActivity {

    private static final Recurrence[] RECURRENCES = {
	Task.Recurrence.ONCE, 
	Task.Recurrence.DAILY, 
	Task.Recurrence.WEEKLY, 
	Task.Recurrence.MONTHLY, 
	Task.Recurrence.YEARLY
    };

    private static final String[] RECURRENCE_STRINGS = {
	"Once",
	"Daily",
	"Weekly",
	"Monthly",
	"Yearly"
    };
    
    private static final String ADD_CATEGORY_TEXT = "Add category...";

    private static final String ADD_TASK_HEADER = "Add Task";
    private static final String EDIT_TASK_HEADER = "Edit Task";

    private static final String ADD_TASK_BUTTON_LABEL = "Add";
    private static final String EDIT_TASK_BUTTON_LABEL = "Save";

    private TaskManager taskManager;
    private Task taskBeingEdited;

    private TextView nameField;
    private TextView descriptionField;
    private Button date;
    private int year;
    private int month;
    private int day;
    private Button add;
    private TextView addressField;

    private Spinner categorySpinner;
    private int previouslySelectedCategoryIndex;
    private Spinner recurrenceSpinner;
    
    private Geocoder geocoder;

    private final int DATE_DIALOG_ID = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.new_task);
	taskManager = ((TaskManagerApplication)(getApplication())).getTaskManager();

	nameField = (TextView) findViewById(R.id.name);
	descriptionField = (TextView) findViewById(R.id.description);
	date = (Button) findViewById(R.id.date);
	addressField = (TextView) findViewById(R.id.address);
	add = (Button) findViewById(R.id.add);

	categorySpinner = (Spinner) findViewById(R.id.taskAddCategorySpinner);
	setUpCategorySpinner();

	recurrenceSpinner = (Spinner) findViewById(R.id.taskAddRecurrenceSpinner);
	setUpRecurrenceSpinner();

	// add a click listener to the button
	OnClickListener buttonListener = new NewTaskActivityButtonListener();
	date.setOnClickListener(buttonListener);
	add.setOnClickListener(buttonListener);

	final Calendar calendar = Calendar.getInstance();
	year = calendar.get(Calendar.YEAR);
	month = calendar.get(Calendar.MONTH);
	day = calendar.get(Calendar.DAY_OF_MONTH);
	
	geocoder = new Geocoder(this);
	
	previouslySelectedCategoryIndex = 0;

	Bundle taskBundle = this.getIntent().getExtras();
	if (taskBundle.isEmpty()) {
	    taskBeingEdited = null;
	    setTitle(ADD_TASK_HEADER);
	    add.setText(ADD_TASK_BUTTON_LABEL);
	} else {
	    long taskID = taskBundle.getLong(TaskViewActivity.TASK_ID_KEY);
	    taskBeingEdited = taskManager.getTask(taskID);

	    nameField.setText(taskBeingEdited.getName());
	    descriptionField.setText(taskBeingEdited.getDescription());

	    double latitude = taskBeingEdited.getLatitude();
	    double longitude = taskBeingEdited.getLongitude();

	    if (LocationHelper.isValidLatitude(latitude) && LocationHelper.isValidLongitude(longitude)) { 
		List<Address> addresses = null;
		
		try {
		    addresses = geocoder.getFromLocation(latitude, longitude, 1);
		} catch (IOException e) {
		    // TODO Auto-generated catch block
		    e.printStackTrace();
		}
		
		Address addr = addresses.get(0);
		int numAddressLines = addr.getMaxAddressLineIndex();
		
		StringBuffer addrString = new StringBuffer();
		for (int i = 0; i < numAddressLines; i++) {
		    addrString.append(addr.getAddressLine(i) + ", ");
		}
		
		addressField.setText(addrString.toString());
	    }

	    Date dueDate = taskBeingEdited.getDueDate();
	    year = dueDate.getYear() + 1900;
	    month = dueDate.getMonth();
	    day = dueDate.getDate();
	    updateDateDisplay();
	    //date.setText(month + "-" + day + "-" + year);

	    recurrenceSpinner.setSelection(Arrays.asList(RECURRENCES).indexOf(taskBeingEdited.getRecurrence()));
	    
	    previouslySelectedCategoryIndex = Arrays.asList(taskManager.getCategories()).indexOf(taskBeingEdited.getCategory());
	    categorySpinner.setSelection(previouslySelectedCategoryIndex);

	    setTitle(EDIT_TASK_HEADER);
	    add.setText(EDIT_TASK_BUTTON_LABEL);
	}
	

    }

    /**
     * sets up a spinner with categories as choices
     */
    private void setUpCategorySpinner() {
	ArrayAdapter<String> categoryAdapter = new ArrayAdapter<String>(this, 
		android.R.layout.simple_spinner_item, 
		new LinkedList<String>());
	
	String[] categories = taskManager.getCategories();
	for (String cat : categories) {
	    categoryAdapter.add(cat);
	}
	
	categoryAdapter.add(ADD_CATEGORY_TEXT);
	
	categoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	categorySpinner.setAdapter(categoryAdapter);
	categorySpinner.setOnItemSelectedListener(new CategorySpinnerListener());
    }
    
    private class CategorySpinnerListener implements OnItemSelectedListener {
	public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
	    if (parent.getAdapter().getItem(pos).equals(ADD_CATEGORY_TEXT)) {
		final EditText input = new EditText(NewTaskActivity.this);
		
		new AlertDialog.Builder(NewTaskActivity.this)
		    .setTitle("Add Category")
		    .setMessage(null)
		    .setView(input)
		    .setPositiveButton("Add", new DialogInterface.OnClickListener() {
		        public void onClick(DialogInterface dialog, int whichButton) {
		            String enteredText = input.getText().toString().trim();
		            
		            if (!enteredText.equals("")) {
		        	taskManager.addCategory(enteredText);
		        	setUpCategorySpinner();
		        	int indexOfCreatedCategory = ((ArrayAdapter)categorySpinner.getAdapter()).getPosition(enteredText);
		        	categorySpinner.setSelection(indexOfCreatedCategory);
		        	previouslySelectedCategoryIndex = indexOfCreatedCategory;
		            } else {
		        	categorySpinner.setSelection(previouslySelectedCategoryIndex);
		            }
		        }
		    }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
		        public void onClick(DialogInterface dialog, int whichButton) {
		            categorySpinner.setSelection(previouslySelectedCategoryIndex);
		        }
		    }).show();
	    }
	}

	public void onNothingSelected(AdapterView<?> arg0) {
	    // TODO Auto-generated method stub
	    
	}
	
    }

    /**
     * sets up a spinner with recurrence options as choices
     */
    private void setUpRecurrenceSpinner() {
	ArrayAdapter<String> recurrenceAdapter = new ArrayAdapter<String>(this, 
		android.R.layout.simple_spinner_item, 
		RECURRENCE_STRINGS);
	recurrenceAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
	recurrenceSpinner.setAdapter(recurrenceAdapter);
    }

    /**
     * creates a date option
     */
    private DatePickerDialog.OnDateSetListener dateSetListener =
	    new DatePickerDialog.OnDateSetListener() {

	public void onDateSet(DatePicker view, int syear, int monthOfYear, int dayOfMonth) {
	    year = syear;
	    month = monthOfYear;
	    day = dayOfMonth;
	    updateDateDisplay();
	}
    };

    /**
     * updates the date shown on the Dialog the activity
     */
    private void updateDateDisplay() {
	date.setText(
		new StringBuilder()
		// Month is 0 based so add 1
		.append(month + 1).append("-")
		.append(day).append("-")
		.append(year).append(" "));
    }

    @Override
    protected Dialog onCreateDialog(int id) {
	switch (id) {
	case DATE_DIALOG_ID:
	    return new DatePickerDialog(this, dateSetListener, year, month, day);
	}
	return null;
    }

    /**
     * Private class for the add button listener
     * 
     * @author Daniel Hull
     *
     */
    private class NewTaskActivityButtonListener implements OnClickListener {

	/**
	 * when ADD is clicked adds a task through the TaskManager class
	 */
	public void onClick(View view) {

	    switch(view.getId()) {
	    case R.id.date:
		showDialog(DATE_DIALOG_ID);
		break;
	    case R.id.add:
		String name = nameField.getText().toString();
		String description = descriptionField.getText().toString();
		String address = addressField.getText().toString();

		Date dueDate = new Date();
		dueDate.setYear(year - 1900);
		dueDate.setMonth(month);
		dueDate.setDate(day);

		double latitude = Task.NO_LOCATION;
		double longitude = Task.NO_LOCATION;

		address = address.trim();
		if (!address.equals("")) {
		    List<Address> addresses = null;
		    
		    try {
			addresses = geocoder.getFromLocationName(address, 1);
		    } catch (IOException e) {
			e.printStackTrace();
		    }
		    
		    if (addresses.size() == 0) {
			showErrorToast("Location is invalid");
			break;
		    }
		    
		    Address a = addresses.get(0);
		    
		    latitude = a.getLatitude();
		    longitude = a.getLongitude();
		}

		Task.Recurrence recurrence = RECURRENCES[recurrenceSpinner.getSelectedItemPosition()];
		String category = taskManager.getCategories()[categorySpinner.getSelectedItemPosition()];

		Task taskToProcess = null;
		if (taskBeingEdited != null) {
		    taskToProcess = taskBeingEdited;
		} else {
		    taskToProcess = new Task();
		}

		taskToProcess.setName(name);
		taskToProcess.setDescription(description);
		taskToProcess.setDueDate(dueDate);
		taskToProcess.setLatitude(latitude);
		taskToProcess.setLongitude(longitude);
		taskToProcess.setRecurrence(recurrence);
		taskToProcess.setCategory(category);

		if (taskBeingEdited != null) {
		    taskManager.updateTask(taskToProcess);
		} else {
		    taskManager.addTask(taskToProcess);
		}

		startUIActivity(getString(R.string.activity_task_view));

		break;
	    }

	}

    }


}
